package com.icloud.cer.rest.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.icloud.cer.rest.Constants;
import com.icloud.cer.rest.common.ContextHolder;
import com.icloud.cer.rest.config.ServerConfigHolder;

public class SessionFilter implements Filter {
	private Log log=LogFactory.getLog(SessionFilter.class);
	   
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		String remoteAddr = request.getRemoteAddr();
		log.debug("remoteAddr:" + remoteAddr);
		boolean isBlack = ServerConfigHolder.getInstance().getBlackIpList().contains(remoteAddr);
		log.debug("url:" + req.getRequestURI());
		if(isBlack && !req.getRequestURI().contains("error.htm")) {
			log.warn("send to error.htm.");
			resp.sendRedirect(req.getContextPath() + "/error.htm?errmsg=ipinblacklist");
			return;
		}
		ContextHolder.initRequest(req, resp);
		request.setCharacterEncoding(Constants.CHARSET.name());
		response.setCharacterEncoding(Constants.CHARSET.name());
		try {
			chain.doFilter(request, response);
		} finally {
			ContextHolder.requestClear();
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader(" x-forwarded-for ");
		log.info("ip:" + ip);
		if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {
			ip = request.getHeader(" Proxy-Client-IP ");
		}
		if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {
			ip = request.getHeader(" WL-Proxy-Client-IP ");
		}
		if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
